package cn.edu.lsnu.mbti.service.impl;

import cn.edu.lsnu.mbti.entity.Page;
import cn.edu.lsnu.mbti.entity.PageUser;
import cn.edu.lsnu.mbti.entity.vo.PageVo;
import cn.edu.lsnu.mbti.exception.CustomerException;
import cn.edu.lsnu.mbti.mapper.PageMapper;
import cn.edu.lsnu.mbti.service.PageService;
import cn.edu.lsnu.mbti.service.PageUserService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author LindaMan
 * @description 针对表【page(页面表)】的数据库操作Service实现
 * @createDate 2022-11-27 19:47:16
 */
@Service
@Slf4j
public class PageServiceImpl extends ServiceImpl<PageMapper, Page>
        implements PageService {

    @Resource
    private PageMapper pageMapper;
    @Resource
    private PageUserService pageUserService;


    /**
     * 保存用户在页面组件上的停留时长和点击次数
     *
     * @param pageVo
     * @return
     */
    @Transactional
    @Override
    public String savePage(PageVo pageVo) {
        try {
            String routeId = pageVo.getRouteId();
            String userId = pageVo.getUserId();
            Integer stayTime = pageVo.getStayTime();
            double t = (double) stayTime / 60;
            //1根据routeId查询page
            LambdaQueryWrapper<Page> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(StrUtil.isNotBlank(routeId), Page::getRouteId, routeId);
            Page page = this.getOne(wrapper);

            //2.使access_total增加1
            pageMapper.increAccessTotal(routeId);

            //3.根据pageId和userId 让count加1 停留时长更新
            LambdaQueryWrapper<PageUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StrUtil.isNotBlank(page.getId()), PageUser::getPageId, page.getId());
            queryWrapper.eq(StrUtil.isNotBlank(userId), PageUser::getUserId, userId);
            PageUser pageUser = pageUserService.getOne(queryWrapper);
            pageUser.setCount(pageUser.getCount() + 1L);
            pageUser.setStayTime(pageUser.getStayTime() + t);
            //保存pageUser
            pageUserService.updateById(pageUser);

            //4.返回
            return "保存成功";
        } catch (Exception e) {
            throw new CustomerException("保存信息失败");
        }
    }
}




